var utils = require('./exports/utils')
var constant = require('./exports/constant')
var point_map = require('./exports/point_map')
var ad_util = require('./exports/ad_util')
var read = {
  items: [],
  index: 0,
  go_page_from_home() {
    this.items = [];
    this.index = 0;
    if (
      !!utils.exists_text("百度") &&
      !!utils.exists_text("视频") &&
      !!utils.exists_text("小说")
    ) {
      console.log("read:go_page_from_home");
      utils.click_text("百度");
      sleep(constant.min_click_after_time * 1000);
      utils.click_text("推荐");
      sleep(constant.min_click_after_time * 1000);
      utils.click_text("推荐");
      sleep(constant.min_click_after_time * 1000);
      this.start();
    } else {
      console.log("read:go_page_from_home: NOT FOUND");
    }
  },
  start() {
    this.items = id("amx").find();
    if (this.items.length > 0) {
      console.log("read start: 找到【id('amx')】 " + this.items.length);
      this.init();
    } else {
      console.log("read start: 没找到【id('amx')】");
      return;
    }
  },
  init() {
    var item = this.items[constant.read_start_index + this.index];
    sleep(constant.min_click_after_time * 1000);
    if (utils.click_ui(item)) {
      console.log("read init: " + this.index + " 点击成功");
      sleep(constant.min_click_after_time * 1000);
      this.execute(constant.read_times);
    } else {
      console.log("read init: " + this.index + " 点击失败");
      this.next();
    }
  },
  execute() {
    var times = constant.read_times;
    var swipe_interval = 400 + random(10, 20);
    while (times > 0) {
      swipe(
        device.width / 2,
        (device.height / 10) * 9,
        device.width / 2,
        (device.height / 10) * 2,
        swipe_interval
      );
      var interval = 1 + random(1, 2);
      sleep(interval * 1000);
      times = times - 1;
    }
    console.log("read execute: end");
    this.after();
  },
  after() {
    console.log("read after");
    back();
    this.next();
  },
  next() {
    this.index = this.index + 1;
    if (this.index > 1) {
      return;
    } else {
      this.init();
    }
  },
};

module.exports = read